/**
 * 文档智能摘要工具 - 历史记录JavaScript
 * 处理历史记录的加载、搜索、导出/导入和删除功能
 */

// 当前页面状态
const state = {
    records: [],
    filteredRecords: [],
    currentPage: 1,
    pageSize: 10,
    searchQuery: ''
};

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化历史记录
    loadHistory();
    
    // 初始化搜索功能
    initSearch();
    
    // 初始化导出/导入功能
    initExportImport();
    
    // 初始化清空功能
    initClearHistory();
});

/**
 * 加载历史记录
 */
async function loadHistory() {
    const loadingIndicator = document.getElementById('loadingIndicator');
    const noRecordsMessage = document.getElementById('noRecordsMessage');
    const tableBody = document.getElementById('historyTableBody');
    
    try {
        loadingIndicator.style.display = 'block';
        noRecordsMessage.style.display = 'none';
        tableBody.innerHTML = '';
        
        const response = await fetch('/api/history');
        const data = await response.json();
        
        if (data.success) {
            state.records = data.records;
            state.filteredRecords = [...state.records];
            
            if (state.records.length === 0) {
                noRecordsMessage.style.display = 'block';
            } else {
                renderHistoryTable();
            }
        } else {
            throw new Error(data.error || '加载历史记录失败');
        }
    } catch (error) {
        console.error('加载历史记录错误:', error);
        showError(error.message);
    } finally {
        loadingIndicator.style.display = 'none';
    }
}

/**
 * 初始化搜索功能
 */
function initSearch() {
    const searchInput = document.getElementById('searchHistory');
    const searchButton = document.getElementById('searchButton');
    
    // 搜索按钮点击事件
    searchButton.addEventListener('click', function() {
        performSearch();
    });
    
    // 输入框回车事件
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
}

/**
 * 执行搜索
 */
function performSearch() {
    const searchInput = document.getElementById('searchHistory');
    state.searchQuery = searchInput.value.trim().toLowerCase();
    
    // 过滤记录
    state.filteredRecords = state.records.filter(record => {
        return record.summary.toLowerCase().includes(state.searchQuery) ||
               record.keywords.some(keyword => keyword.toLowerCase().includes(state.searchQuery)) ||
               record.source.toLowerCase().includes(state.searchQuery);
    });
    
    // 重置页码并重新渲染
    state.currentPage = 1;
    renderHistoryTable();
}

/**
 * 渲染历史记录表格
 */
function renderHistoryTable() {
    const tableBody = document.getElementById('historyTableBody');
    const noRecordsMessage = document.getElementById('noRecordsMessage');
    
    // 计算分页
    const start = (state.currentPage - 1) * state.pageSize;
    const end = start + state.pageSize;
    const pageRecords = state.filteredRecords.slice(start, end);
    
    // 清空表格
    tableBody.innerHTML = '';
    
    if (state.filteredRecords.length === 0) {
        noRecordsMessage.style.display = 'block';
        return;
    }
    
    noRecordsMessage.style.display = 'none';
    
    // 添加记录行
    pageRecords.forEach(record => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${formatDateTime(record.date)}</td>
            <td>${truncateText(record.summary, 100)}</td>
            <td>${record.keywords.map(keyword => `<span class="badge bg-primary">${keyword}</span>`).join(' ')}</td>
            <td>${record.source}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="showDetail('${record.id}')">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteRecord('${record.id}')">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tableBody.appendChild(row);
    });
}

/**
 * 显示记录详情
 * @param {string} id - 记录ID
 */
async function showDetail(id) {
    const record = state.records.find(r => r.id === id);
    if (!record) return;
    
    // 填充模态框内容
    document.getElementById('detailSummary').textContent = record.summary;
    document.getElementById('detailOriginal').textContent = record.original;
    document.getElementById('detailDate').textContent = formatDateTime(record.date);
    document.getElementById('detailRatio').textContent = (record.ratio * 100) + '%';
    document.getElementById('detailSource').textContent = record.source;
    document.getElementById('detailId').textContent = record.id;
    
    // 显示关键词
    const keywordsContainer = document.getElementById('detailKeywords');
    keywordsContainer.innerHTML = '';
    record.keywords.forEach(keyword => {
        keywordsContainer.appendChild(createKeywordBadge(keyword));
    });
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('detailModal'));
    modal.show();
}

/**
 * 删除记录
 * @param {string} id - 记录ID
 */
async function deleteRecord(id) {
    if (!confirm('确定要删除这条记录吗？')) return;
    
    try {
        const response = await fetch(`/api/history/${id}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 从状态中移除记录
            state.records = state.records.filter(r => r.id !== id);
            state.filteredRecords = state.filteredRecords.filter(r => r.id !== id);
            
            // 重新渲染表格
            renderHistoryTable();
            showSuccess('记录已删除');
        } else {
            throw new Error(data.error || '删除记录失败');
        }
    } catch (error) {
        console.error('删除记录错误:', error);
        showError(error.message);
    }
}

/**
 * 初始化导出/导入功能
 */
function initExportImport() {
    // 导出按钮
    const exportButton = document.getElementById('exportHistory');
    exportButton.addEventListener('click', exportHistory);
    
    // 导入按钮
    const importButton = document.getElementById('importButton');
    importButton.addEventListener('click', importHistory);
}

/**
 * 导出历史记录
 */
async function exportHistory() {
    try {
        // 创建导出数据
        const exportData = {
            version: '1.0',
            date: new Date().toISOString(),
            records: state.records
        };
        
        // 创建下载链接
        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `summary-history-${new Date().toISOString().slice(0,10)}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showSuccess('历史记录已导出');
    } catch (error) {
        console.error('导出历史记录错误:', error);
        showError('导出历史记录失败');
    }
}

/**
 * 导入历史记录
 */
async function importHistory() {
    const fileInput = document.getElementById('importFile');
    const mergeCheckbox = document.getElementById('mergeRecords');
    const file = fileInput.files[0];
    
    if (!file) {
        showError('请选择要导入的文件');
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('merge', mergeCheckbox.checked);
        
        const response = await fetch('/api/history/import', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 关闭导入模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('importModal'));
            modal.hide();
            
            // 重新加载历史记录
            await loadHistory();
            showSuccess('历史记录已导入');
        } else {
            throw new Error(data.error || '导入历史记录失败');
        }
    } catch (error) {
        console.error('导入历史记录错误:', error);
        showError(error.message);
    }
}

/**
 * 初始化清空历史记录功能
 */
function initClearHistory() {
    const clearButton = document.getElementById('clearHistory');
    const confirmButton = document.getElementById('confirmClearButton');
    
    clearButton.addEventListener('click', function() {
        const modal = new bootstrap.Modal(document.getElementById('confirmClearModal'));
        modal.show();
    });
    
    confirmButton.addEventListener('click', async function() {
        try {
            const response = await fetch('/api/history', {
                method: 'DELETE'
            });
            
            const data = await response.json();
            
            if (data.success) {
                // 清空状态
                state.records = [];
                state.filteredRecords = [];
                
                // 关闭确认模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('confirmClearModal'));
                modal.hide();
                
                // 重新渲染表格
                renderHistoryTable();
                showSuccess('历史记录已清空');
            } else {
                throw new Error(data.error || '清空历史记录失败');
            }
        } catch (error) {
            console.error('清空历史记录错误:', error);
            showError(error.message);
        }
    });
}